package com.fastCms.business.frame.utils;

import com.fastCms.business.frame.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 杭州人参大健康管理有限公司 版权所有 © Copyright 2019<br>
 *
 * @Description: <br>
 * @Project: healthyPro <br>
 * @CreateDate: Created in 2019/5/13 下午2:06 <br>
 * @Author: <a href="lsquan@healthpro.vip">lsquan</a>
 */
@Slf4j
public class RedisUtil {
    private static StringRedisTemplate stringRedisTemplate;

    // @Value("${spring.redis.database}")
    private static int database = 0;

    public static StringRedisTemplate getRedisTemplate(int dbIndex) {
        try {
            return selectDb(dbIndex);
        } catch (BusinessException e) {
            log.error("[redisUtil]--------redis切换失败------reason:stringRedisTemplate=null", e.getMessage());
        }
        return null;
    }

    public static StringRedisTemplate getRedisTemplate() {
        try {
            return selectDb(database);
        } catch (BusinessException e) {
            log.error("[redisUtil]--------redis切换失败------reason:stringRedisTemplate=null", e.getMessage());
        }
        return null;
    }

    public static void save(String key, String value) {
        stringRedisTemplate.boundValueOps(key).set(value);
    }

    public static void save(String key, String value, long timeout, TimeUnit unit) {
        stringRedisTemplate.boundValueOps(key).set(value, timeout, unit);
    }

    public static void increment(String key) {
        stringRedisTemplate.opsForValue().increment(key);
    }

    public static String get(String key) {
        return stringRedisTemplate.boundValueOps(key).get();
    }

    private static StringRedisTemplate selectDb(int index) throws BusinessException {
        stringRedisTemplate = ApplicationContextUtil.getBean("stringRedisTemplate");
        if (stringRedisTemplate == null) {
            log.error("[redisUtil]--------redis切换失败------reason:stringRedisTemplate=null");
            return null;
        }
        JedisConnectionFactory factory =
            (JedisConnectionFactory) stringRedisTemplate.getConnectionFactory();
        factory.setDatabase(index);//dbindex DB切换
        return stringRedisTemplate;
    }
}
